Код ошибки 2280

This snippet is compiled without errors in Visual Studio 2013 (Version 12.0.31101.00 Update 4)

class A
{
public:
   A(){}
   A(A &&){}
};

int main(int, char*)
{
   A a;
   new A(a);
   return 0;
}

while it is compiled with this error in Visual Studio 2015 RC (Version 14.0.22823.1 D14REL):

1>------ Build started: Project: foo, Configuration: Debug Win32 ------
1>  foo.cpp
1>c:\dev\foo\foo.cpp(11): error C2280: 'A::A(const A &)': attempting to reference a deleted function
1>  c:\dev\foo\foo.cpp(6): note: compiler has generated 'A::A' here
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I think that the compiler shipped with Visual Studio 2015 generates the Copy Constructor and marks it as =delete and so I get the error C2280 (which, by the way, I cannot find documented on msdn.microsoft.com).

Now, let’s say I have a codebase which is compilable with Visual Studio 2013 (and it works because it relies on the code generated automatically by the compiler) but not compilable with Visual Studio 2015 due to C2280, how can I fix the problem?

I was thinking to declare class A in this way:

class A
{
public:
   A(){}
   A(A &&){}
   A(const A&)=default;
};

am I missing something?

asked Jul 7, 2015 at 9:37

Alessandro Jacopson's user avatar

2

From [class.copy]/7, emphasis mine:

If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly.
If the class definition declares a move constructor or move assignment operator, the implicitly declared copy
constructor is defined as deleted
; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if
the class has a user-declared copy assignment operator or a user-declared destructor.

There is an equivalent section with similar wording for copy assignment in paragraph 18. So your class is really:

class A
{
public:
   // explicit
   A(){}
   A(A &&){}

   // implicit
   A(const A&) = delete;
   A& operator=(const A&) = delete;
};

which is why you can’t copy-construct it. If you provide a move constructor/assignment, and you still want the class to be copyable, you will have to explicitly provide those special member functions:

    A(const A&) = default;
    A& operator=(const A&) = default;

You will also need to declare a move assignment operator. If you really have a need for these special functions, you will also probably need the destructor. See Rule of Five.

answered Jul 7, 2015 at 10:38

Barry's user avatar

I had the same problem and it was due to a poorly defined member variable:

double const deltaBase = .001;

Putting this in will cause the copy constructor to be deleted. Get rid of the «const» and assign in the constructor.

answered May 30, 2016 at 3:14

doby's user avatar

dobydoby

5454 silver badges9 bronze badges

3

I encountered the same error, just because I had misused std::unique_ptr.

Note that std::unique_ptr is non-copyable, it is only moveable.

Here is the wrong demonstration.

class word;
class sentence
{
    public:
        sentence();
        ~sentence();

    public:
        // Wrong demonstration, because I pass the parameter by value/copying
        // I should use 'std::shared_ptr< word >' instead.
        sentence(std::initializer_list< std::unique_ptr< word > > sentence);
};

The following code is taken from MSVC compiler’s STL library. We can see that the copy constructor and copy assignment operator of class unique_ptr are deleted explicitly.

    unique_ptr(const unique_ptr&) = delete;
    unique_ptr& operator=(const unique_ptr&) = delete;

answered Sep 27, 2020 at 15:43

QingJia Wang's user avatar

1

I was stuck with this error even after «default»ing the copy ctor. Turned out, one of my class member (rapidjson’s Document object) was disallowing copy. Changed it to a reference, initialized via a *(new rapidjson::Document()) in the default ctor’s initializer list. Looks like all individual members should also be copy’able in addition to the defaulted copy ctor.

answered Aug 19, 2019 at 13:00

Neelabh Mam's user avatar

Neelabh MamNeelabh Mam

3006 silver badges10 bronze badges

If you write a user-defined move constructor for your class, the copy constructor will be deleted. This is because if a class needs special behaviour for its move constructor, it probably needs some similar behaviour in its copy constructor, so the copy constructor will be deleted to stop you from inadvertently using the default behaviour.

If you want to define your own move constructor and use the default copy constructor, you need to declare it as default, like you suggested in your question:

class A
{
public:
   A(){}
   A(A &&){}
   //I know what I'm doing, compiler, use the default version.
   A(const A&)=default;
};

Note that if you define a custom move constructor, you should think about your assignment operators and destructor as well.

answered Jul 7, 2015 at 9:44

TartanLlama's user avatar

TartanLlamaTartanLlama

63.8k13 gold badges158 silver badges194 bronze badges

1

I ran into a similar situation where I had a hierarchy of classes and a destructor in the base class was declared virtual. In this case, compiler does NOT automatically generate move and copy constructors. So we have to default these in order for compiler to generate the definitions for these methods.

However, I ran into another issue after I defaulted copy and move constructor. I saw that the compiler was still not able to generate copy and move constructors. The reason was the usage of std::atomic member variable in the base class. Since atomic variable are not copy able or movable, the compiler could not generate definitions for copy constructor. This gave me lot of headache and I had to solve the problem using a different method.
See other great answers for similar issue that I faced.

References:
Does a default virtual destructor prevent compiler-generated move operations?

Error with copy constructor/assignment operator for a class which has std::atomic member variable

answered Oct 31, 2019 at 23:35

piyu2cool's user avatar

I faced this issue today and mine was caused by having both std::stringstream and std::ostream as member variables. I initially thought this was caused because I accidentally named one of them as sstream which was the name for the header file <sstreamn> I had included previously.

But changing the name didn’t help, and I had to remove the ostream variable completely for this to work again! then I realized I had declared it incorrectly like this:

std::ostream some_stream;

while it should have been :

...
std::ostream some_stream(&filebuf);

Basically, I was much better off using ofstream instead!

answered Oct 3, 2020 at 12:52

Hossein's user avatar

HosseinHossein

24.3k35 gold badges121 silver badges225 bronze badges

0

I went through some old code that used raw pointers and changed them to unique_ptrs instead. Now, when I try to compile the code, I get this error message:

Error 1 error C2280: ‘std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)’ : attempting to reference a deleted function d:\visual studio 2013\vc\include\xmemory0

The compiler output about the situation is huge — to save space in this question, see it here.

As far as I can tell, it has something to do with the way I use the unique pointers. It starts from here (level.h, lines 65-66):

typedef std::unique_ptr<Enemy> PEnemy;
std::list<PEnemy> m_enemies;

Now, the next clue I get in the compiler output is the line 47 in basesource.cpp:

std::list<PEnemy> enemies = Game::LEVEL->getEnemies();

Why does this cause problems? How can I fix the error?

BartoszKP's user avatar

BartoszKP

34.8k15 gold badges102 silver badges130 bronze badges

asked Oct 22, 2014 at 10:57

manabreak's user avatar

1

unique_ptrs cannot be copied; only moved! But since std::list should be able to move them around internally, your only problem should be that assignment you’re performing to the list itself.

Can you move the list?

  • std::list<PEnemy> enemies = std::move(Game::LEVEL->getEnemies());

Or use a reference to it instead?

  • const std::list<PEnemy>& enemies = Game::LEVEL->getEnemies();

If not (and it will depend on the return type of Game::LEVEL->getEnemies() as to which, if either, of the above solutions you can use), you’re going to need to do a deep, deep copy or switch to shared_ptr instead.

This all may seem to be a hindrance, but it’s actually doing you a favour by keeping the rules regarding ownership of your pointees strictly enforced.

answered Oct 22, 2014 at 11:02

Lightness Races in Orbit's user avatar

3

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Icon Ex Номер ошибки: Ошибка 2280
Название ошибки: Microsoft Access Error 2280
Описание ошибки: You have added more output formats to the Windows Registry than Microsoft Office Access can initialize.@Some output formats will not be available. Remove those formats that you never or least often use.@@1@@@1.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Access
Относится к: Windows XP, Vista, 7, 8, 10, 11

Сводка «Microsoft Access Error 2280

«Microsoft Access Error 2280» также считается ошибкой во время выполнения (ошибкой). Программисты работают через различные уровни отладки, пытаясь убедиться, что Microsoft Access как можно ближе к безошибочным. Как и во всем в жизни, иногда такие проблемы, как ошибка 2280, упускаются из виду.

В выпуске последней версии Microsoft Access может возникнуть ошибка, которая гласит: «You have added more output formats to the Windows Registry than Microsoft Office Access can initialize.@Some output formats will not be available. Remove those formats that you never or least often use.@@1@@@1.». После того, как об ошибке будет сообщено, Microsoft Corporation отреагирует и быстро исследует ошибки 2280 проблемы. Затем Microsoft Corporation будет иметь знания, чтобы исследовать, как и где устранить проблему. Следовательно, разработчик будет использовать пакет обновления Microsoft Access для устранения ошибки 2280 и любых других сообщений об ошибках.

Что запускает ошибку времени выполнения 2280?

У вас будет сбой во время выполнения Microsoft Access, если вы столкнетесь с «Microsoft Access Error 2280» во время выполнения. Рассмотрим распространенные причины ошибок ошибки 2280 во время выполнения:

Ошибка 2280 Crash — программа обнаружила ошибку 2280 из-за указанной задачи и завершила работу программы. Если данный ввод недействителен или не соответствует ожидаемому формату, Microsoft Access (или OS) завершается неудачей.

Утечка памяти «Microsoft Access Error 2280» — если есть утечка памяти в Microsoft Access, это может привести к тому, что ОС будет выглядеть вялой. Потенциальным фактором ошибки является код Microsoft Corporation, так как ошибка предотвращает завершение программы.

Ошибка 2280 Logic Error — Вы можете столкнуться с логической ошибкой, когда программа дает неправильные результаты, даже если пользователь указывает правильное значение. Когда точность исходного кода Microsoft Corporation низкая, он обычно становится источником ошибок.

Microsoft Access Error 2280 проблемы часто являются результатом отсутствия, удаления или случайного перемещения файла из исходного места установки Microsoft Access. Как правило, любую проблему, связанную с файлом Microsoft Corporation, можно решить посредством замены файла на новую копию. Кроме того, регулярная очистка и оптимизация реестра Windows предотвратит создание неправильных ссылок на пути к файлам Microsoft Corporation, поэтому мы настоятельно рекомендуем регулярно выполнять сканирование реестра.

Распространенные сообщения об ошибках в Microsoft Access Error 2280

Эти проблемы Microsoft Access, связанные с Microsoft Access Error 2280, включают в себя:

  • «Ошибка приложения Microsoft Access Error 2280.»
  • «Недопустимая программа Win32: Microsoft Access Error 2280»
  • «Извините за неудобства — Microsoft Access Error 2280 имеет проблему. «
  • «Microsoft Access Error 2280 не может быть найден. «
  • «Microsoft Access Error 2280 не найден.»
  • «Ошибка запуска программы: Microsoft Access Error 2280.»
  • «Файл Microsoft Access Error 2280 не запущен.»
  • «Ошибка Microsoft Access Error 2280. «
  • «Ошибка в пути к программному обеспечению: Microsoft Access Error 2280. «

Проблемы Microsoft Access Microsoft Access Error 2280 возникают при установке, во время работы программного обеспечения, связанного с Microsoft Access Error 2280, во время завершения работы или запуска или менее вероятно во время обновления операционной системы. Выделение при возникновении ошибок Microsoft Access Error 2280 имеет первостепенное значение для поиска причины проблем Microsoft Access и сообщения о них вMicrosoft Corporation за помощью.

Эпицентры Microsoft Access Error 2280 Головные боли

Проблемы Microsoft Access и Microsoft Access Error 2280 возникают из отсутствующих или поврежденных файлов, недействительных записей реестра Windows и вредоносных инфекций.

Особенно ошибки Microsoft Access Error 2280 проистекают из:

  • Недопустимая (поврежденная) запись реестра Microsoft Access Error 2280.
  • Файл Microsoft Access Error 2280 поврежден от вирусной инфекции.
  • Вредоносное удаление (или ошибка) Microsoft Access Error 2280 другим приложением (не Microsoft Access).
  • Другая программа, конфликтующая с Microsoft Access Error 2280 или другой общей ссылкой Microsoft Access.
  • Неполный или поврежденный Microsoft Access (Microsoft Access Error 2280) из загрузки или установки.

Продукт Solvusoft

Загрузка
WinThruster 2023 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

Я новичок в разработке игр и очень плохо знаком с c ++, но я начал разрабатывать небольшую игру Arkanoid. У меня это было запущено ранее, но после рефакторинга (введение класса ArkanoidGame) он не компилируется, и я не могу понять, почему.

Я получаю ошибку:

d:\dropbox\development\gamedev\c++\arkanoid\arkanoid\main.cpp(14): error C2280:
'ArkanoidGame::ArkanoidGame(void)' : attempting to reference a deleted function
d:\dropbox\development\gamedev\c++\arkanoid\arkanoid\arkanoidgame.h(25) :
compiler has generated 'ArkanoidGame::ArkanoidGame' here

Я просто не понимаю, что это значит, и понятия не имею, что делать, чтобы это исправить.

Я включил рассматриваемые классы:

main.cpp:

#include "ArkanoidGame.h"
int main() {
ArkanoidGame game;
game.init(800, 600);
while (game.isRunning()) {
game.checkInput();
game.checkCollisions();
game.draw();
}
return 0;
}

Arkanoid.h:

#include "Ball.h"#include "Pad.h"#include <SFML/Graphics.hpp>
#include <stdarg.h>
#include <memory>

class ArkanoidGame
{
private:
bool running;
public:
void ArkanoidGame::init(int, int);
bool ArkanoidGame::isRunning();
void ArkanoidGame::checkCollisions();
void ArkanoidGame::checkInput();
void ArkanoidGame::update();
void ArkanoidGame::draw();
sf::RenderWindow* window;
Pad pad;
Ball ball;
};

ArkanoidGame.cpp:

#include "ArkanoidGame.h"
void ArkanoidGame::init(int windowWidth, int windowHeight) {
window = new sf::RenderWindow(sf::VideoMode(windowWidth, windowHeight), "Arkanoid!");
window->setFramerateLimit(60);

ArkanoidGame::running = true;

//Init pad
pad = Pad((float)(windowWidth / 2), (float)(windowHeight - 50));

//Init ball
ball = Ball(0.f, 0.f);
}

template<class T1, class T2> bool intersect(T1& mA, T2& mB) {
return mA.right() >= mB.left() && mA.left() <= mB.right()
&& mA.bottom() >= mB.top() && mA.top() <= mB.bottom();
}

void ArkanoidGame::checkCollisions() {
if (!intersect(pad, ball)) return;

ball.velocity.y = -ball.ballVelocity;

if (ball.x() < pad.x()) {
ball.velocity.x = -ball.ballVelocity;
}
else {
ball.velocity.x = ball.ballVelocity;
}
}

void ArkanoidGame::update() {
//Update positions
pad.update(window->getSize().x);
ball.update(window->getSize().x, window->getSize().y);
}

void ArkanoidGame::draw() {
window->clear(Color::Black);
window->draw(pad.getShape());
window->draw(ball.getShape());
window->display();
}

void ArkanoidGame::checkInput() {
if (Keyboard::isKeyPressed(Keyboard::Key::Escape)) {
running = false;
}
}

bool ArkanoidGame::isRunning() {
return running;
}

10

Решение

Предположительно, либо Pad или же Ball (или оба) не имеет конструктора по умолчанию; поэтому нельзя создать класс, который их содержит. Они должны быть инициализированы с использованием одного из объявленных конструкторов.

Лучшее решение состоит в том, чтобы удалить ваш странный init и замените его конструктором:

ArkanoidGame(int windowWidth, int windowHeight) :
running(true),
window(new ...),
Pad(windowWidth / 2, windowHeight - 50),
Ball(0,0)
{
window->setFramerateLimit(60);
}

int main() {
ArkanoidGame game(800, 600);
// ...
}

Если по какой-то причине вы действительно хотите двухэтапный танец инициализации, вам нужно будет предоставить конструкторы по умолчанию для обоих Pad а также Ball, Я не рекомендовал бы это все же; есть меньше возможностей для ошибок, если объект не может быть создан в недопустимом состоянии.

14

Другие решения

Я думаю, что проблема в том, что либо класс Pad, либо класс Ball не имеют конструктора по умолчанию (у вас есть два члена dtat этих классов в определении класса ArkanoidGame: Pad pad; и Ball ball;)
, В этом случае компилятор определил конструктор по умолчанию класса ArkanoidGame как удаленный (в противном случае он будет некорректным). Однако в первой строке главного

ArkanoidGame game;

вы пытаетесь вызвать конструктор по умолчанию класса ArkanoidGame.

Примите также во внимание, что объявления функций-членов должны иметь безусловные имена в определении класса.
Так, например, это объявление

void ArkanoidGame::init(int, int);

является недействительным. Должен быть

void init(int, int);

5

Вы должны предоставить конструктор для ArkanoidGame. В Arkanoid.h:

ArkanoidGame ();

В Arkanoid.cpp:

ArkanoidGame::ArkanoidGame ()
{
// it is better to initialize members in the constructor,
// although not strictlynecessary
running = false;
}

3

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Код ошибки 2271
  • Код ошибки 2270 шевроле нива
  • Код ошибки 2349 плагин госуслуги
  • Код ошибки 2269
  • Код ошибки 2349 компас

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии