gpt4 book ai didi

c++ - 将构造函数转换为函数的返回值

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:48:30 26 4
gpt4 key购买 nike

是否可以使用转换构造函数而不是复制构造函数从函数返回对象,即使没有 RVO 进化(假设编译器不支持任何此类优化)?问题的关键是 C++ std 告诉了什么,有人能告诉我吗?我得到了 gcc 并编译了下面的代码,并在评论中提出了几个问题。



class A
{
public:
A(int) {};
A(int, int) {};

private:
A(const A &) = delete;
A & operator = (const A &) = delete;
};

A foo(void)
{// All the CEs below are all the same, which is 'using the deleted function 'A::A(const A&)''.
//return(0); // Not compiled.
//return(A(0)); // Not compiled. ok since the A isn't be copy-able.
//return {0}; // Compiled. Is it a bug of the compiler?
//return({0}); // Not compiled. What happened when returns in '()' implemented?
//return 0; // Not compiled. What happened when returns without '()' and '{}' implemented?
//return ({0, 0}); // Not compiled.
return {0, 0}; // Compiled. Realy??

/*
1. What are the differences in 'return 0', 'return {0}', 'return(0)' and 'return({0})'?
2. Is it any possible to do conversion from source type object 'which is 'int' in this sample' to returning type of
the function directly with only ONE constructor call even if the compiler has no any copying eliminating optimization
but full compatibility with STD? Note that the function 'foo' here has no returning object accepter.
*/
}

int main(void)
{
foo(); // Note that there is no accepter of 'A' here, it's not discussing purpose at this topic of the post.
}

// compiling with the gcc ver. 4.8.1.

最佳答案

是的,如果您使用花括号初始化列表来初始化返回的对象,那么在返回语句中调用转换构造函数是完全有效的。

C++11 标准在 6.6.3 [stmt.return] 中这样说:

The value of the expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy or move of a temporary object (12.2). [Note: A copy or move operation associated with a return statement may be elided or considered as an rvalue for the purpose of overload resolution in selecting a constructor (12.8). — end note] A return statement with a braced-init-list initializes the object or reference to be returned from the function by copy-list-initialization (8.5.4) from the specified initializer list. [Example:

std::pair<std::string,int> f(const char* p, int x) {
return {p,x};
}

end example]

在其他注释掉的 return 语句中,您创建了一个临时对象,然后需要将该对象复制到返回的对象,这需要一个可访问的复制构造函数。

关于c++ - 将构造函数转换为函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19200076/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com