为什么我的复制构造函数不起作用?
Why doesn't my copy constructor work?
这可能很容易,但我有点困惑。我遇到了一些问题,我的矢量表现不好,现在看来我找到了罪魁祸首。这是我的Player
类的淡化版本。
class Player {
private:
std::string _firstName;
std::string _lastName;
public:
Player(std::string firstName, std::string lastName) {
_firstName = firstName;
_lastName = lastName;
};
Player(const Player& otherPlayer) {
_firstName = otherPlayer._firstName.c_str();
_lastName = otherPlayer._lastName.c_str();
std::cout << "Created " << _firstName << " " << _lastName << std::endl; // Why doesn't _firstName and _lastName contain anything?
};
std::string GetName() { return _firstName + " " + _lastName; };
};
int main(int argc, const char * argv[])
{
Player player1 = Player("Bill", "Clinton");
Player player2 = Player(player1);
std::cout << "Player: " << player2.GetName() << std::endl;
return 0;
}
输出是微薄的Player:
。我不知道为什么我的复制构造函数没有做我希望它做的事情,特别是考虑到这样的建议(Zac Howland的评论解释了c_str();
部分)。我是否违反了三条规则(顺便说一句,我还没有完全清醒过来)?如果有人能给我指明正确的方向,我将不胜感激!
它适用于我:http://ideone.com/aenViu
我刚刚添加了:
#include <iostream>
#include <string>
但有一件事我不明白:
_firstName = otherPlayer._firstName.c_str();
_lastName = otherPlayer._lastName.c_str();
为什么选择.c_str()
?您将string
转换为char*
以将其分配给新的string
?
EDIT:Zac Howland在评论中指出:"在C++11之前,如果你想确保你的字符串被复制(而不是引用计数),你必须使用c_str()
方法来强制它复制字符串。新标准消除了这一点,但如果他使用的是旧的编译器,或者还没有完全实现C++11的编译器,它将确保深度复制。"
只需:
_firstName = otherPlayer._firstName;
_lastName = otherPlayer._lastName;
而且,你真的需要这个复制构造函数吗?默认会做你想做的事我想。。。
此外,不是分配成员:
Player(std::string firstName, std::string lastName) {
_firstName = firstName;
_lastName = lastName;
}
请改用成员初始化列表:
Player(std::string firstName, std::string lastName) :
_firstName( std::move(firstName) ),
_lastName( std::move(lastName) )
{}
在第一种情况下,调用字符串的默认构造函数,然后调用字符串的复制赋值运算符,与直接调用复制构造函数的第二种情况相比,肯定会有(轻微的)效率损失。
最后一件事,在可能的情况下,不将值作为方法参数传递,传递引用,甚至在不需要修改时传递常量引用:
Player( const std::string& firstName, const std::string& lastName )
// ^^^^^ ^ ^^^^^ ^
: _firstName( firstName ) // no move here, since args are constant references
, _lastName( lastName )
{}
所有修改的工作实例。
相关文章:
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 通过构造函数创建一些值并尝试添加到文档中使用 rapidjson 不起作用
- 类和构造函数中的函数根本不起作用,并且不返回任何错误
- 为什么必须使用'*p=a',而使用'p=&a'在构造函数中不起作用
- QObject::连接不起作用 - 使用函数语法找不到信号
- 模板 ctor 类型推导不起作用(没有匹配的构造函数用于初始化 ...)与函数<>参数
- 将复制构造函数设置为默认值在继承自 QObject 时不起作用
- 子类化 STL 容器:范围构造函数不起作用
- 带有此指针的模板类多重继承构造函数不起作用?
- 从数组中删除元素不起作用的函数
- VS为我提供了对构造函数的另一个解决方案,但我想知道为什么我的工作不起作用
- 模板参数在具有相同数据类型的单个类型名的构造函数中不起作用
- 隐式用户定义的转换不起作用,因为在编译C 时无法识别运算符和转换构造函数
- C++:在没有 lvalue 的情况下调用时复制构造函数不起作用
- 调用 setVisible(false) 在 QWidget 的构造函数中不起作用
- 模板堆栈类的复制构造函数中的 pop() 和 push() 不起作用
- 为什么我的右值复制构造函数不起作用
- 如果所述结构具有构造函数,则带有 new[] 的结构数组似乎不起作用
- 在Visual C++中不起作用的函数的取消映射
- C++将东西移到一个不起作用的函数中