我已经研究了堆栈溢出的相关问题,据我所知,main()中的第一行应该调用构造函数,第二行应该触发一次移动构造函数的调用(或者当移动构造函数被移除时复制构造函数)。
#include <iostream>
#include <memory>
using namespace std;
class Node {
public:
Node() { cout << "Called contructor\n"; }
~Node() { cout << "Called destructor\n"; }
Node(const Node& other) { cout << "Called copy-contructor\n"; }
Node(Node&& other) { cout << "Called move-constructor\n"; }
};
int main(){
Node a = Node();
make_shared<Node>(a);
return 0;
}但我从上面的代码中得到的结果是:
Called contructor
Called copy-contructor
Called move-constructor
Called destructor
Called destructor
Called destructor在我看来,复制构造函数是由于参数传递而调用的,而移动构造函数是在make_shared的实现中调用的,对吗?在调用make_shared (例如,使用指针的引用传递)时,有可能避免两次构造函数调用吗?有没有办法总共只用一个构造函数调用就能得到一个shared_ptr<Node>?
我的编译器版本:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: x86_64-apple-darwin20.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin代码是使用默认参数g++ test.cpp编译的
发布于 2021-08-04 06:01:35
似乎只有在默认语言版本低于c++11的情况下使用g++ test.cpp时才会出现此结果。使用g++ -std=c++11 test.cpp编译时,输出为:
Called contructor
Called copy-contructor
Called destructor
Called destructor它遵守了标准。
我认为一种可能的解释是,当编译器检测到c++语法时,它不会更改为相应的语言版本,而是使用某种“技巧”来规避编译器错误,但这并不遵循语言标准。
https://stackoverflow.com/questions/68645226
复制相似问题